package com.example.demo.controller;

import com.example.demo.common.AppConstant;
import com.example.demo.common.JsonResult;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Dish;
import com.example.demo.entity.vo.DishVO;
import com.example.demo.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private ThreadPoolTaskExecutor workPool;

    // 校验 排序参数 的合法性
    private static String checkSort(Integer sort) {
        if (sort != null) {
            switch (sort) {
                case 0:
                    return "asc";
                case 1:
                    return "desc";
            }
        }
        return null;
    }

    // 用户获取菜品列表, 只能获取上架的菜品
    @RequestMapping("/getlist")
    public JsonResult getList(String inputValue, String typeName,
                           Integer priceSort, Integer gradeSort,
                              Integer pSize, Integer pIndex) throws ExecutionException, InterruptedException {
        return JsonResult.success(getDishMap(1, inputValue, typeName, checkSort(priceSort), checkSort(gradeSort), pSize, pIndex));
    }

    // 实现分页查询菜品列表
    private HashMap<String, Object> getDishMap(Integer state, String inputValue, String typeName,
                                          String priceSort, String gradeSort,
                                               Integer pSize, Integer pIndex) throws ExecutionException, InterruptedException {
        // 1. 校正参数, 参数不合法的情况下
        if (pSize == null || pSize <= 1) {
            pSize = 10;
        }
        if (pIndex == null || pIndex <= 0) {
            pIndex = 1;
        }
        // 2. 计算 offset
        pIndex = (pIndex - 1) * pSize;


        // 3. 获取菜品列表
        Integer finalPSize = pSize;
        Integer finalPIndex = pIndex;
        FutureTask<List<DishVO>> getDishList = new FutureTask<>(() -> {
            return dishService.getList(state, inputValue, typeName, priceSort, gradeSort, finalPSize, finalPIndex);
        });
        workPool.submit(getDishList);
        // 4. 获取总页数
        FutureTask<Integer> getCount = new FutureTask<>(() -> dishService.getCount(state, inputValue, typeName, priceSort, gradeSort));
        workPool.submit(getCount);
        // 5. 业务组装，返回结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("dishList", getDishList.get());
        map.put("pageCount", Math.ceil(getCount.get() * 1.0 / finalPSize));
        return map;
    }

    // 管理员获取菜品列表
    @RequestMapping("/admin/getlist")
    public JsonResult adminGetList(Integer state, String inputValue, String typeName,
                                   Integer priceSort, Integer gradeSort,
                                   Integer pSize, Integer pIndex) throws ExecutionException, InterruptedException {
        return JsonResult.success(getDishMap(state, inputValue, typeName, checkSort(priceSort), checkSort(gradeSort), pSize, pIndex));
    }

    @RequestMapping("/admin/add")
    public JsonResult add(Dish dish) {
        // 添加菜品，菜品名称 和 菜品价格 不能为空
        if (dish == null || !StringUtils.hasLength(dish.getDishName()) || dish.getPrice() == null) {
            return JsonResult.failure(-1, "非法参数");
        }
        if (dish.getState() != null) {
            if (dish.getState() != 0 && dish.getState() != 1) {
                return JsonResult.failure(-1, "非法参数");
            }
        }
        return JsonResult.success(dishService.add(dish));
    }

    @RequestMapping("/admin/update")
    public JsonResult update(Dish dish) {
        System.out.println(dish);
        // 菜品 id 不能为空
        if (dish == null || dish.getId() == null) {
            return JsonResult.failure(-1, "非法参数");
        }
        // 其他字段至少一个不为空
        if (dish.getPrice() == null && dish.getState() == null && dish.getTypeId() == null && !StringUtils.hasLength(dish.getDishName())) {
            return JsonResult.failure(-1, "非法参数");
        }
        // state 只能为 -1， 0， 1
        if (dish.getState() != null) {
            if (dish.getState() != -1 && dish.getState() != 0 && dish.getState() != 1) {
                return JsonResult.failure(-1, "非法参数");
            }
        }
        return JsonResult.success(dishService.update(dish));
    }

    @RequestMapping("/admin/delete")
    public JsonResult delete(Integer dishId) {
        if (dishId == null || dishId <= 0) {
            return JsonResult.failure(-1, "非法参数");
        }
        return JsonResult.success(dishService.delete(dishId));
    }

    @RequestMapping("/orderDetail")
    public JsonResult orderDetail(HttpServletRequest request, Integer orderId) {
        if (orderId == null || orderId <= 0) {
            return JsonResult.failure(-1, "非法参数");
        }
        return JsonResult.success(dishService.getListByOrderId(orderId, UserSessionUtils.getUserId(request)));
    }

    @RequestMapping("/admin/orderDetail")
    public JsonResult adminOrderDetail(Integer orderId) {
        if (orderId == null || orderId <= 0) {
            return JsonResult.failure(-1, "非法参数");
        }
        return JsonResult.success(dishService.getListByOrderId(orderId, null));
    }

    @RequestMapping("/admin/photo")
    public JsonResult updatePhoto(Integer dishId, @RequestPart("photo") MultipartFile file) throws IOException {
        if (dishId == null || dishId <= 0) {
            return JsonResult.failure(-1, "非法参数");
        }

        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        if (!".jpg".equals(fileName) && !".png".equals(fileName)) {
            return JsonResult.failure(-1, "上传头像图片只能是 JPG 或 PNG 格式！");
        }

        String filePath = AppConstant.DISH_DIR + "/" + UUID.randomUUID() + fileName;
        file.transferTo(new File(filePath));
        filePath = filePath.substring(filePath.indexOf("/images"));
        Dish dish = new Dish();
        dish.setId(dishId);
        dish.setPhoto(filePath);
        return JsonResult.success(dishService.update(dish));
    }
}
